package com.jprocms.module.cms.framework.operatelog.core;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.jpro.framework.common.util.collection.CollectionUtils;
import com.jprocms.module.cms.dal.dataobject.content.ContentDO;
import com.jprocms.module.cms.service.content.ContentService;
import com.mzt.logapi.service.IParseFunction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

/**
 * 批量获取内容标题的 {@link IParseFunction} 实现类
 *
 * @author JPROCMS
 */
@Slf4j
@Component
public class ContentBatchParseFunction implements IParseFunction {

    public static final String NAME = "getContentTitlesById";

    @Resource
    private ContentService contentService;

    @Override
    public String functionName() {
        return NAME;
    }

    @Override
    public String apply(Object value) {
        if (StrUtil.isEmptyIfStr(value)) {
            return "";
        }

        // 获取内容信息
        final Collection<Long> ids = (Collection<Long>) value;
        final List<ContentDO> contentList = contentService.getContentList(ids);
        if (CollUtil.isEmpty(contentList)) {
            //彻底删除查不到内容但是需要记录行为
            if (CollUtil.isNotEmpty(ids)) {
                return StrUtil.join("[,]", ids);
            }
            log.warn("[apply][获取内容{{}}为空", value);
            return "";
        }
        final List<String> titles = CollectionUtils.convertList(contentList, ContentDO::getTitle);
        return StrUtil.join("[,]", titles);
    }

}
